package com.its.common.config;

import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * @author xiaxp
 */
public class CorsFilterConfig{
  private static final String ALL = "*";

  @Bean
  @ConditionalOnMissingBean(CorsFilter.class)
  public CorsFilter corsFilter() {
    //1、添加CORS配置信息
    CorsConfiguration config = new CorsConfiguration();
    //2、允许写的域
//    config.addAllowedOriginPattern(ALL);
    config.addAllowedOrigin(ALL);
    //3、是否发送cookie信息
    config.setAllowCredentials(Boolean.TRUE);
    //4、允许的请求方式
    config.addAllowedMethod("OPTIONS");
    config.addAllowedMethod("GET");
    config.addAllowedMethod("POST");
    config.addAllowedMethod("HEAD");
    config.addAllowedMethod("PUT");
    config.addAllowedMethod("DELETE");
    config.addAllowedMethod("PATCH");
    config.addAllowedMethod(ALL);
    //5、允许的头信息
    config.addAllowedHeader(ALL);
    //6、有效时长
    config.setMaxAge(3600L);
    //7、添加映射路径,拦截一切请求
    UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
    configSource.registerCorsConfiguration("/**",config);

    // 配置前端js允许访问的自定义响应头
//    config.addExposedHeader("AuthToken");
//    config.addExposedHeader("Token");
//    config.addExposedHeader("SpecialToken");

    //8、返回新的CorsFilter
    return new CorsFilter(configSource);
  }
}
